<script setup>
import { ref, reactive, onMounted, watch, computed } from 'vue'
// import { guides } from './homeData.js'
import { showToast } from 'vant';
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useClickAway, useEventListener } from '@vant/use';
// import { useStore } from 'vuex'

import { useUser } from '@/composition/useUser'
import { setBg } from '@/plugins/util';

const { user, loggedIn, logout } = useUser();

const guides = user.value.extInfo.guides;

const router = useRouter();
// const store = useStore();

// do not use same name with ref
const searchKey = ref('')

const search = (searchKey) => {
  console.log('searchKey:', searchKey)
  let by = 'https://cn.bing.com/search?q=' + searchKey
  window.open(by)
}

const guideClick = (url) => {
  console.log('guideClick url:', url)
  window.open(url)
}

const downBg = () => {
  let bodyEle = document.querySelector('.bgbox')
  let backgroundImage = bodyEle.style.backgroundImage;
  backgroundImage = backgroundImage.substring(backgroundImage.indexOf('"') + 1, backgroundImage.lastIndexOf('"'))
  console.log(backgroundImage)
  window.open(backgroundImage)
}

const yiyan = ref({})

const getYiyan = () => {
  axios.get('https://v1.hitokoto.cn/')
    .then(function (response) {
      // 处理成功情况
      // console.log('response', response.data);
      yiyan.value = response.data
    })
    .catch(function (error) {
      // 处理错误情况
      console.log('error', error);
    })
}


onMounted(() => {
  // guides.value.forEach(guide => {
  //   let icon = guide.icon;
  //   if (icon === '') {
  //     // background=transparent
  //     icon = 'https://ui-avatars.com/api/?&rounded=true&font-size=0.33&name=' + guide.name
  //     guide.icon = icon
  //   }
  // })

  getYiyan();
  setBg();

  // let localUser = localStorage.getItem('user');
  // if (localUser == undefined || localUser == '') {
  //   // 如果 localStorage 没有用户数据 就用  vue store 里面的默认数据
  //   localStorage.setItem('user', JSON.stringify(store.state.user.info))
  // } else {
  //   // 把 localStorage 里面的数据同步到 vue store
  //   store.commit('user/setUser', JSON.parse(localUser));
  // }


})

const offset = ref({ x: -1, y: -1 });

const loading = ref(false);
const onRefresh = () => {
  setTimeout(() => {
    showToast('刷新成功');
    loading.value = false;
  }, 1000);
};


const menuShow = ref(false);

const activeMenu = ref(-1);
const menuChange = (index) => {
  // menuShow.value = false;
  menuShow.value = false;
  console.log('removeEventListener')
  document.removeEventListener('click', handlerClick);
};


const menuDom = ref();
const animationendFunEnd = ref(false);
// useClickAway(menuDom, () => {
//   // console.log('click outside!');
//   // // menuShow.value = false
//   // if (animationendFunEnd.value) {
//   //   menuShow.value = false
//   //   // animationendFunEnd.value = false
//   // }
//   menuShow.value = false
// });

// 在 body 元素上绑定 click 事件
// useEventListener(
//   'click',
//   (event) => {
//     console.log('click body');
//     console.log(menuDom.value)
//     let isSelf = menuDom.value.contains(event.target)  // 这个是自己的区域
//     if (!isSelf) {
//       console.log('没在区域里面-->>>')
//     } else {
//       console.log('在区域里--->>>>>')
//     }
//   },
//   { target: document.body },
// );

const handlerClick = (event) => {
  let isSelf = menuDom.value?.contains(event.target)  // 这个是自己的区域
  if (!isSelf) {
    console.log('没在区域里面-->>>');
    menuShow.value = false;
    console.log('removeEventListener')
    document.removeEventListener('click', handlerClick)
  } else {
    console.log('在区域里--->>>>>');
  }
}


const addLis = () => {
  if (menuShow.value) {
    // 只有菜单显示的时候 才需要绑定事件
    console.log('removeEventListener')
    document.removeEventListener('click', handlerClick)

    console.log('addEventListener')
    document.addEventListener('click', handlerClick);
  }
}

// watch(
//   () => menuShow,
//   () => {
//     console.log(menuShow.value)
//     if (menuShow.value) {
//       // 只有菜单显示的时候 才需要绑定事件
//       console.log('removeEventListener')
//       document.removeEventListener('click', handlerClick)

//       console.log('addEventListener')
//       document.addEventListener('click', handlerClick);
//     }
//   },
//   {
//     deep: true
//   }
// );


const animationendFun = () => {
  console.log('animationend end')
  animationendFunEnd.value = true;
}


const userName = computed(() => {
  if (loggedIn.value) {
    return user.value.baseInfo.userName
  }
  return '立即登陆'
})

// watch(
//   () => store.state.user.info,
//   (userNew, useOld) => {
//     debugger;
//     if(userNew.baseInfo.userCode != '-1') {
//       userName.value = userNew.baseInfo.userName
//     }
//   },
//   {
//     deep: true
//   }
// );


</script>

<template>
  <div class="menuicon" @click="menuShow = true" v-show="!menuShow">
    <van-icon name="arrow" size="20" />
  </div>

  <!-- 左滑进入 -->
  <transition name="van-slide-left">
    <!-- @animationstart="animationendFunEnd = false" @animationend="animationendFunEnd = true" -->
    <!-- @animationstart="addLis()" -->
    <div class="menu" v-show="menuShow" ref="menuDom" @animationstart="addLis()">
      <div class="user" @click="router.push('/user')">
        <van-icon name="manager-o" size="30" />
        <span>{{ userName }}</span>
      </div>
      <van-sidebar v-model="activeMenu" @change="menuChange">
        <!--        <van-sidebar-item title="login" to="/login"/>-->
        <van-sidebar-item title="背景设置" to="/bgSet" />
        <van-sidebar-item title="导航设置" to="/guideSet" />
      </van-sidebar>

      <div class="save-bg" @click="downBg()">
        <!--        <van-floating-bubble v-model:offset="offset" axis="xy" icon="down" magnetic="x" :gap="5" @click="downBg()"/>-->
        <van-icon name="down" size="15" />
        <span>保存背景</span>
      </div>
    </div>
  </transition>





  <div class="search">
    <van-search v-model="searchKey" @search="search" background="transparent">
    </van-search>
  </div>

  <div class="row">
    <div class="col" v-for="(guide, idx) in guides" :url="guide.url" :index="idx" @click="guideClick(guide.url)">
      <div class="indexItem">
        <van-image width="2.5rem" height="2.5rem" fit="contain" position="center" :src="guide.icon" />
        <div class="name">{{ guide.name }}</div>
      </div>
    </div>
  </div>

  <div class="yiyan" v-show="yiyan && yiyan.hitokoto">
    <div class="yiyanDe" onclick="window.location.reload()">
      <span>{{ yiyan.hitokoto + ' from ' + yiyan.from }}</span>
    </div>
  </div>

  <!-- <van-popover v-model:show="showPopover" theme="dark" :actions="actions">
    <template #reference>
      <van-floating-bubble v-model:offset="offset" axis="xy" icon="down" magnetic="x"  gap="5" @click="downBg()"/>
    </template>
  </van-popover> -->




  <van-pull-refresh v-model="loading" @refresh="onRefresh"></van-pull-refresh>
</template>

<style scoped>
.menuicon {
  position: fixed;
  left: 10px;
  top: 10px;
  cursor: pointer;
  background-color: rgb(255, 255, 255, 0.4);
  padding: 5px;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.menu {
  position: fixed;
  left: 0;
  top: 0;
  cursor: pointer;
  width: 50vw;
  max-width: 300px;
  height: 100vh;
  background-color: rgb(255, 255, 255, 0.6);
  z-index: 99;
}


.user {
  cursor: pointer;
  height: 80px;
  display: flex;
  justify-content: left;
  align-items: center;
  padding: 0 15px;
  background-color: rgb(255, 255, 255, 0.8);
}

.user>span {
  font-size: 14px;
  margin-left: 10px;
}

.save-bg {
  cursor: pointer;
  height: 30px;
  display: flex;
  justify-content: left;
  align-items: center;
  padding: 0 15px;
  position: absolute;
  bottom: 5px;
}

.save-bg>span {
  font-size: 10px;
  margin-left: 10px;
}


.search {
  margin: 0 auto;
  max-width: 500px;
  margin-top: 30vh;
  color: white;
}

.row {
  margin: 20px auto;
  /* max-width: 90vw; */
  max-width: 800px;
  display: grid;
  grid-template-columns: repeat(auto-fit, 80px);
  grid-row-gap: 10px;
  justify-content: center;
  align-content: center;
  align-items: start;
}

.col {
  max-width: 80px;
  cursor: pointer;
}

.col:hover {
  translate: 0 -5px;
}


.indexItem {
  display: grid;
  justify-items: center;
  align-items: start;
  row-gap: 0.5rem;
}

.name {
  font-size: 10px;
  color: white;
  background-color: rgba(0, 0, 0, 0.3);
  padding: 0.2rem;
  border-radius: 0.4rem;
}


:deep(.van-search__field) {
  height: 42px;
}

:deep(.van-search__content) {
  background: rgb(0, 0, 0, 0.6);
  box-shadow: 0 0 5px 1px #999;
  border-radius: 5px;
}

:deep(.van-field__control) {
  color: white;
}


.yiyan {
  position: fixed;
  bottom: 40px;
  left: 10px;
  right: 10px;

  text-align: center;

  display: flex;
  justify-content: center;

}

.yiyanDe {
  color: white;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 0.4rem;
  padding: 8px;
  cursor: pointer;
}

.yiyanDe:hover {
  translate: 0 -5px;
}

.yiyanDe>span {
  font-size: 12px;
  /* white-space: nowrap; */
  /* overflow: hidden; */
  /* text-overflow: ellipsis; */
}
</style>
